package com.sgb.merchant.view.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.merchant.R;
import com.swgk.core.base.CallBack;
import com.swgk.core.dialog.ImagesPreviewDialog;
import com.swgk.core.util.GlideEngine;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PicImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final LayoutInflater mLayoutInflater;
    private CallBack callBack;
    private Context mContext;
    /**
     * 选择图片后返回的LocalMedia
     **/
    private List<LocalMedia> mData;
    /**
     * 本地文件List
     **/
    private List<File> fileList;
    /**
     * 网络图片和本地图片地址组合在一起的List
     **/
    private ArrayList<String> urls;
    /**
     * 网络图片地址List
     **/
    private List<String> neImgList;
    private Intent intent;
    /**
     * 上传图片的最大张数
     **/
    private int maxSize;
    /**
     * 脚布局
     **/
    private int TYPE_FOOT = 1001;
    /**
     * 是否有弹窗 0：无    1：有
     **/
    private int type;
    public ISelectPop iSelectPop;
    public delClickListener delClickListener;
    public addClickListener addClickListener;

    public void setAddClickListener(PicImageAdapter.addClickListener addClickListener) {
        this.addClickListener = addClickListener;
    }

    public void setDelClickListener(PicImageAdapter.delClickListener delClickListener) {
        this.delClickListener = delClickListener;
    }

    public interface ISelectPop {
        void openPop();
    }

    public void OnSelectPop(ISelectPop iSelectPop) {
        this.iSelectPop = iSelectPop;
    }

    public PicImageAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
    }

    public PicImageAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize, CallBack callBack) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
        this.callBack = callBack;
    }

    /**
     * 需要弹窗调用
     *
     * @param context
     * @param data
     * @param urls
     * @param maxSize
     * @param type
     */
    public PicImageAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize, int type) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
        this.type = type;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_FOOT) {
            View headerView = mLayoutInflater.inflate(R.layout.merchant_item_device_foot, parent, false);
            return new FootViewHolder(headerView);
        }
        View inflate = mLayoutInflater.inflate(R.layout.merchant_item_image_publish, parent, false);
        return new ViewHolder(inflate);

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ViewHolder) {
            //如果地址包含http，就用网络加载图片的方式
            Glide.with(mContext).load(urls.get(position)).apply(new RequestOptions().placeholder(R.mipmap.morentu_change) ).into(((ViewHolder) holder).img);
            //点击图片
            ((ViewHolder) holder).img.setOnClickListener(view -> openPhotoView(position));

            //点击删除按钮
            ((ViewHolder) holder).delView.setOnClickListener(v -> {
                if (urls.get(position).contains("http") || urls.get(position).contains("https")) {
                    //移除网络图片
                    neImgList.remove(position);
                } else if (urls.get(position).contains("storage/emulated")) {
                    //移除本地LocalMedia  position减去网络图片的长度等于本地图片的位置
                    mData.remove(position - neImgList.size());
                    //移除对应的文件
                    fileList.remove(position - neImgList.size());
                }
                if (delClickListener != null) {
                    delClickListener.del(position);
                }
                urls.remove(position);
                notifyDataSetChanged();
            });
        } else if (holder instanceof FootViewHolder) {
            ((FootViewHolder) holder).add_rl.setOnClickListener(v -> {
                if (urls.size() == maxSize) {
                    MToast.showToast(mContext, "最多选择" + maxSize + "张图片");
                } else {
                    if (type == 0) {
                        if(addClickListener!=null){
                            addClickListener.add();
                        }
                        openAlbum();
                    } else {
                        iSelectPop.openPop();
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        if (maxSize == 1 || urls.size() == 0) {
            return 1;
        } else if (maxSize != urls.size()) { //加了头布局,多一个
            return urls.size() + 1;
        } else {
            return urls.size();
        }


    }

    @Override
    public int getItemViewType(int position) {
        //在第一个位置添加头
        if (urls.size() != 0) {
            if (urls.size() != maxSize && position == urls.size()) {//当添加图片没到达张数，加头布局
                return TYPE_FOOT;
            }
        } else {
            if (position == 0) {
                return TYPE_FOOT;
            }
        }
        return super.getItemViewType(position);
    }

    //设置本地图片
    public void setDatas(List<LocalMedia> mData, List<String> urls) {
        //防止图片重复  可优化
        this.urls.clear();
        this.urls.removeAll(urls);
        if (neImgList.size() != 0) {
            this.urls.addAll(neImgList);
        }/* else {
            this.urls.clear();
        }*/
        this.urls.addAll(urls);
        this.mData = mData;
        notifyDataSetChanged();
    }

    /**
     * 设置图片文件List
     **/
    public void setFileList(List<File> fileList) {
        this.fileList = fileList;
    }

    /**
     * 设置网络图片List
     */
    public void setNetImgList(List<String> netImgList) {
        if (netImgList == null) {
            this.neImgList = new ArrayList<>();
        } else {
            this.neImgList = netImgList;
            this.urls.addAll(netImgList);
        }
        notifyDataSetChanged();
    }

    /**
     * 删除网络图片List
     */
    public void removeNetImgList(List<String> albumList) {
        for (int i = 0; i < neImgList.size(); i++) {
            for (int j = 0; j < urls.size(); j++) {
                if (urls.get(j).equals(neImgList.get(i))) {
                    urls.remove(j);
                }
            }
        }
//        urls.removeAll(neImgList);
        notifyDataSetChanged();
    }

    /**
     * 获取已选择的本地文件List
     **/
    public List<File> getFileList() {
        return this.fileList;
    }

    /**
     * 获取所有的地址List，包括网络和本地
     **/
    public ArrayList<String> getUrls() {
        return urls;
    }

    /**
     * 获取网络图片地址List
     **/
    public List<String> getNetUrls() {
        return neImgList;
    }

    /**
     * 获取已选择的LocalMedia List
     **/
    public List<LocalMedia> getLocalMedia() {
        return mData;
    }

    /**
     * 预览
     *
     * @param position
     */
    private void openPhotoView(int position) {
        if (intent == null) {
            intent = new Intent();
        }
        ImagesPreviewDialog.newInstance(urls, position).show(mContext);
    }

    /**
     * 尾布局的viewholder
     */
    class FootViewHolder extends RecyclerView.ViewHolder {
        RelativeLayout add_rl;

        FootViewHolder(View itemView) {
            super(itemView);
            add_rl = itemView.findViewById(R.id.add_rl);
        }
    }


    /**
     * 正常内容的viewholder
     */
    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView img;
        ImageView delView;

        ViewHolder(View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.photo_img);
            delView = itemView.findViewById(R.id.delete_tv);
        }
    }

    public void openAlbum() {
        if (callBack != null) {
            callBack.onFailed(0, 0, "选择图片");
        }
        PictureSelector.create((Activity) mContext)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(maxSize - neImgList.size())//判断还能选多少张图片
                .imageEngine(GlideEngine.createGlideEngine())
                .compress(true)//是否压缩
                .minimumCompressSize(1024 * 10)//小于10M不压缩
                .selectionMedia(mData)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    public interface delClickListener {
        void del(int position);
    }

    public interface addClickListener {
        void add();
    }
}